<?php

class Admin_Table_Orders extends Apk_Db_Table
{
	protected $_name      = 'foods_orders';
    protected $_primary   = 'id';
    protected $_ERROR = '';

    public function GetError()
    {
    	return $this->_ERROR;
    }

    public function GetDataList($page=1, $sort=null, $page_count=null, $params=null)
    {
    	$sel = $this->getAdapter()->select()
    		  ->from($this->_name, array('id', 'id_num' => 'id', 'phone', 'email', 'total','add_date', 'is_active'))
    		  ->where('is_removed = 0');


		if(count($params) > 0)
		foreach($params as $k => $v)
		{
			switch ($k)
			{
				case 'is_active':
					if(intval($v) >= 0 && trim($v) != '')
					$sel->where($this->_name.'.'.$k.' = ?', intval($v));
					break;
				case 'search_text':
					if(trim($v) != '')
					$sel->where($this->_name.'.email like "%'.trim($v).'%" or '.$this->_name.'.phone like "%'.trim($v).'%"');
					break;
				default:
					if(intval($v) > 0)
					$sel->where($this->_name.'.'.$k.' = ?', $v);
			}
		}

		if(!is_null($sort) && strlen($sort) > 0) $sel->order($this->_name.'.'.$sort);
		else $sel->order($this->_name.'.add_date desc');


    	return $this->setDecorator('simpleDecorator')->getPager($sel, $page, array('perPage' => $page_count));
    }

    public function GetDataRow($id)
    {
    	$sel = $this->getAdapter()->select()
    				->from($this->_name)
    				->where('id = ?', $id);

    	return $this->setDecorator('simpleDecorator')->getList($sel)->getRow(0)->toArray();
    }


    public function GetItemsByOrder($id)
    {
    	$sel = $this->getAdapter()->select()
    				->from('foods_ordered_items')
    				->join('foods_menu', 'foods_menu.id = foods_ordered_items.id_menu', array('menu_idt' => 'idt'))
    				->where('foods_ordered_items.id_order = ?', $id);

    	$data =  $this->setDecorator('simpleDecorator')->getList($sel)->toArray();



    	return $data;
    }



    //*******************
    // insert/update/delete

	public function insert(array $data, $user_id)
    {

    	$data['add_date'] = time();
    	$data['modify_date'] = time();
        return parent::insert($data);
    }

    public function update(array $data, $id, $user_id)
    {
		$data['modify_date'] = time();
    	return parent::update($data, 'id = '.$id);
    }

    public function remove($items, $user_id)
    {
    	foreach($items as $k => $id)
    	{
	    	$data['modify_date'] = time();
	    	$data['is_removed'] = 1;

	    	parent::update($data, 'id = '.$id);
    	}

    	return true;
	}


    /********************
     ***  Decorators  ***
    *********************/

    public function simpleDecorator($key, $value)
    {
        switch ($key) {
            case 'public_date':
            case 'modify_date':
            case 'add_date':
            	$result[$key]['__attributes'] = $this->timestampToArray($value);
            	break;
            default:
                $result[$key] = stripslashes($value);
                break;
        }
        return $result;
    }

}
?>